package autoupdate.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import static autoupdate.test.AutoUpdateConstants.*;

import common.test.Module;

public class AutoUpdater{
	private static List<Module> staleModules; 
	
	public static String UPDATE_FILE_SUFFIX = ".upd";
	
	public static String UPDATE_REPLACEMENT_SUFFIX = "";
	
	public static boolean checkForUpdates(){
		staleModules = VersionFileReaderV2.getModuleUpdateList();
		
		int moduleCount = staleModules.size();
		if(moduleCount > 0)
			return true;
		else
			return false;
	}
	
	public static void printFileList(){
		File dir = new File(".");
		
//		 This filter only returns directories
	    FilenameFilter fileFilter = new FilenameFilter() {
	        public boolean accept(File dir, String name) {
	            return name.indexOf(UPDATE_FILE_SUFFIX) > -1;
	        }
	    };

	    
	    String[] children = dir.list(fileFilter);
	    if (children == null) {
	        // Either dir does not exist or is not a directory
	    } else {
	        for (int i=0; i<children.length; i++) {
	            // Get filename of file or directory
	            String filename = children[i];
	            System.out.println(filename);
	        }
	    }
	}
	
	public static void printUpdateSites(){
//		 set up default properties
		Properties updateSites = new Properties();
		FileInputStream stream;
		try{
			stream = new FileInputStream(UPDATE_SITE_FILE);
			updateSites.load(stream);
			stream.close();
			
			Collection<Object> collection = updateSites.values();
			Iterator<Object> i = collection.iterator();
			Object o;
			while(i.hasNext()){
				o = i.next();
				System.out.println(o);
			}
		}catch(FileNotFoundException e){
			// TODO Auto-generated catch block
			e.printStackTrace();
		}catch(IOException e){
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	public static void downloadUpdates(){
		DLoadUpdates.downloadUpdates(staleModules);
	}
	
	public static boolean isJumpStarterPatched(){
		int moduleCount = staleModules.size();
		for(int i = 0; i < moduleCount; i++){
			if(staleModules.get(i).getModuleFilename().equals("JumpStarter.jar"))
				return true;
		}
		return false;
	}
}
